using System.Text.RegularExpressions;
using Gateway.Common.Enums;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Gateway.UI.Api.Filters.Attributes;

/// <summary>
/// 日志属性aop
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class LogAttribute : Attribute, IFilterMetadata
{
    /// <summary>
    /// 
    /// </summary>
    public LogTypeEnum LogType { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public string LogEvent { get; set; }

    /// <summary>
    /// 要解析的字段 多个以逗号分割
    /// </summary>
    public List<string> Regex { get; set; }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logType"></param>
    /// <param name="logEvent"></param>
    public LogAttribute(LogTypeEnum logType, string logEvent = default)
    {
        Regex = Match(logEvent, "(?<=\\$\\{)(.+?)(?=\\})");
        LogType = logType;
        LogEvent = logEvent;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="s"></param>
    /// <param name="p"></param>
    /// <returns></returns>
    private List<string> Match(string s, string p)
    {
        if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(p)) return [];
        s = s.Replace(" ", "");
        var matches = System.Text.RegularExpressions.Regex.Matches(s, p, RegexOptions.IgnoreCase);
        if (matches.Count <= 0)
            return [];
        return matches.Select(item => item.Value).ToList();
    }
}